package org.jflame.fx.util;

import java.util.List;
import java.util.function.Function;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.ComboBox;
import javafx.util.StringConverter;

public class DataBinds {

    /**
     * 绑定一个Map到Combox. map被转换为{@code List<KeyValuePair>},map的key作为Combox条目的显示文本
     * 
     * @param <K>
     * @param <V>
     * @param cbx
     * @param dataItems
     */
    /* public static <K,V> ObservableList<KeyValuePair<K,V>> bindToCombox(ComboBox<KeyValuePair<K,V>> cbx,
            Map<K,V> dataItems) {
        List<KeyValuePair<K,V>> pairs = KeyValuePair.fromMap(dataItems);
        ObservableList<KeyValuePair<K,V>> items = FXCollections.observableArrayList(pairs);
        cbx.setItems(items);
        cbx.setConverter(new KVPairStringConverter<>());
        return items;
    }
    
    public static <K,V> void bindToCombox(ComboBox<KeyValuePair<K,V>> cbx, List<KeyValuePair<K,V>> dataItems) {
        ObservableList<KeyValuePair<K,V>> items = FXCollections.observableArrayList(dataItems);
        cbx.setItems(items);
        cbx.setConverter(new KVPairStringConverter<>());
    }*/

    /**
     * 绑定一个集合到ComboBox
     * 
     * @param <T>
     * @param cbx
     * @param dataItems
     * @param mapper 从集合元素获取一个属性作为Combox条目的显示文本,为null则文本是对象的toString()
     * @return
     */
    public static <T> void bindToCombox(ComboBox<T> cbx, List<T> dataItems, Function<? super T,String> mapper) {
        ObservableList<T> items = FXCollections.observableArrayList(dataItems);
        cbx.setItems(items);
        if (mapper != null) {
            cbx.setConverter(new StringConverter<T>() {

                @Override
                public String toString(T object) {
                    return mapper.apply(object);
                }

                @Override
                public T fromString(String string) {
                    return null;
                }
            });
        }
    }
}
